<?php

namespace Caisse\CaisseBundle\Controller;

use Caisse\CaisseBundle\Entity\Tables;
use Caisse\CaisseBundle\Form\TablesType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class TablesController extends Controller {

    public function listTableMobileAction() {
        $em = $this->getDoctrine()->getManager();
        $request = $this->getRequest();
        $id = $request->get('id');
        $tables = $em->getRepository("CaisseBundle:Tables")->getTableServeur($id);

        $resultat = array();
        $resultat['tables'] = array();
        foreach ($tables as $table) {

            $tab = array();
            $tab['numTable'] = $table->getNumTable();
            $tab ['id'] = $table->getId();
            if ($table->getServeur() != null) {
                $tab ['etatTable'] = 1;
            } else {
                $tab ['etatTable'] = 0;
            }

            $resultat['tables'][] = $tab;
        }
        return new Response(json_encode($resultat));
        //aaaaaaaaaaaaaaaaa
    }

    public function listTablesAction() {
        $em = $this->getDoctrine()->getManager();
        $tables = $em->getRepository("CaisseBundle:Tables")->findAll();

        return $this->render('CaisseBundle:Tables:listTables.html.twig', array(
                    'tables' => $tables,
        ));
    }

    public function ajoutTablesAction() {
        $em = $this->getDoctrine()->getManager();
        $request = $this->getRequest();
        $id = $request->get('id');
        if ($id != "")
            $table = $em->getRepository('CaisseBundle:Tables')->find($id);
        else
            $table = new Tables();

        $form = $this->createForm(new TablesType(), $table);


        if ($request->isMethod('POST')) {
            $form->bind($request);
            if ($form->isValid()) {
                $table = $form->getData();


                $repository = $em->getRepository('CaisseBundle:Tables');
                $em->persist($table);
                $em->flush();
                $tables = $repository->findAll();
                return $this->redirect($this->generateUrl("caisse_acceuil"));
            }
        }
        return $this->render('CaisseBundle:Tables:ajoutTable.html.twig', array('form' => $form->createView(), 'id' => $id));
    }

    public function supprimerTablesAction() {
        $request = $this->getRequest();
        $id = $request->get('id');
        $em = $this->getDoctrine()->getManager();
        $table = $em->getRepository('CaisseBundle:Tables')->find($id);
        $em->remove($table);
        $em->flush();
        $url = $this->generateUrl("caisse_list_table");
        return $this->redirect($url);
    }

}
